<?php
import('cerberus.interface.ICache');
import('cerberus.util.Text');
/**
 * Default caching system using files
 *
 * @author André Silva
 */
class Cache implements ICache {
	/**
	 * Get the full file path for a key
	 * @param string $key
	 * @return string
	 */
	private static function getPath($key) {
		return APPLICATION_PATH.'/cache/'.Text::encode($key);
	}

	/**
	 * Get the cached value for a key
	 * @param string $key
	 * @return mixed
	 */
	public static function get($key) {
		$filename = self::getPath($key);
		if (file_exists($filename)) {
			$data = unserialize(file_get_contents($filename));
			if ($data['ttl']==0 || (time() - $data['ttl']) < filemtime($filename)) {
				return $data['value'];
			} else {
				self::delete($key);
			}
		}
		return null;
	}

	/**
	 * Cache a value for a key
	 * @param string $key
	 * @param mixed $value
	 * @param integer $ttl
	 */
	public static function set($key, $value, $ttl = 0) {
		$filename = self::getPath($key);
		$data = array('value'=>$value,'ttl'=>$ttl);
		file_put_contents($filename, serialize($data));
	}

	/**
	 * Check if exists a value cached for a key
	 * @param string $key
	 * @return boolean
	 */
	public static function exists($key) {
		return self::get($key) !== null;
	}

	/**
	 * Remove a cached value for a key
	 * @param string $key
	 * @return boolean
	 */
	public static function delete($key) {
		$filename = self::getPath($key);
		if (file_exists($filename)) {
			return unlink($filename);
		}
	}
}
?>
